from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List, Optional

mcp = FastMCP("Galera MCP Server")

"""
Galera MCP Server - 面向 Galera Cluster 的 garbd 组件命令行操作

MCP tools 列表：
1. galera_garbd_daemon - 启动 garbd 守护进程
   参数：group, address, name, sst, donor, log_file, options, config_file
   返回：执行结果 JSON

2. galera_garbd_help - 显示 garbd 帮助信息
   参数：无
   返回：执行结果 JSON

3. galera_garbd_version - 显示 garbd 版本信息  
   参数：无
   返回：执行结果 JSON

4. galera_service_manage - 管理 garbd 系统服务
   参数：action, service_name
   返回：执行结果 JSON
"""

@mcp.tool()
def galera_garbd_daemon(
    group: str,
    address: str = "gcomm://0.0.0.0",
    name: Optional[str] = None,
    sst: Optional[str] = None,
    donor: Optional[str] = None,
    log_file: Optional[str] = None,
    options: Optional[str] = None,
    config_file: Optional[str] = None
) -> dict:
    """
    启动 garbd 守护进程
    
    参数:
        group: 组名称（必需）
        address: 集群地址，默认 "gcomm://0.0.0.0"
        name: 节点名称
        sst: 状态快照传输方法
        donor: 捐赠者名称
        log_file: 日志文件路径
        options: 额外选项字符串
        config_file: 配置文件路径
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    cmd_parts = ["garbd", "-d"]
    
    if group:
        cmd_parts.extend(["-g", group])
    
    if address:
        cmd_parts.extend(["-a", address])
    
    if name:
        cmd_parts.extend(["-n", name])
    
    if sst:
        cmd_parts.extend(["--sst", sst])
    
    if donor:
        cmd_parts.extend(["--donor", donor])
    
    if log_file:
        cmd_parts.extend(["-l", log_file])
    
    if options:
        cmd_parts.extend(["-o", options])
    
    if config_file:
        cmd_parts.extend(["-c", config_file])
    
    command = " ".join(cmd_parts)
    
    try:
        result = subprocess.run(
            cmd_parts,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def galera_garbd_help() -> dict:
    """
    显示 garbd 帮助信息
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = "garbd -h"
    
    try:
        result = subprocess.run(
            ["garbd", "-h"],
            capture_output=True,
            text=True,
            timeout=10
        )
        
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def galera_garbd_version() -> dict:
    """
    显示 garbd 版本信息
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    command = "garbd -v"
    
    try:
        result = subprocess.run(
            ["garbd", "-v"],
            capture_output=True,
            text=True,
            timeout=10
        )
        
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def galera_service_manage(action: str, service_name: str = "garbd") -> dict:
    """
    管理 garbd 系统服务
    
    参数:
        action: 操作类型 (restart/enable/reload)
        service_name: 服务名称，默认 "garbd"
    
    返回:
        JSON 结构: {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    valid_actions = ["restart", "enable", "reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} {service_name}",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Must be one of {valid_actions}"
        }
    
    command = f"systemctl {action} {service_name}"
    
    try:
        result = subprocess.run(
            ["systemctl", action, service_name],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()